<?php

namespace app\admin\controller\workteam\analysis;

use app\admin\model\AuthGroup;
use app\admin\model\workteam\Accountlog;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;


/**
 * 项目分析
 */
class Project extends Backend
{
    protected $model = null;
    protected $searchFields = 'id,username,nickname';
    protected $groupList = [];
    private $projectids;
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->getGroupData();
        $this->assignconfig("admin", ['id' => $this->auth->id]);

    }

    protected function getGroupData()
    {

        $department = get_addon_info('department');
        if ($department && $department['state'] == 1) {
            $groupdata = \app\admin\model\department\Admin::getAllDepartmentsTreeArray($this->auth->id, $this->auth->isSuperAdmin());
        } else {
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
            $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
            Tree::instance()->init($groupList);
            $groupdata = [];
            if ($this->auth->isSuperAdmin()) {
                $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
                foreach ($result as $k => $v) {
                    $groupdata[$v['id']] = $v['name'];
                }
            } else {
                $result = [];
                $groups = $this->auth->getGroups();
                foreach ($groups as $m => $n) {
                    $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                    $temp = [];
                    foreach ($childlist as $k => $v) {
                        $temp[$v['id']] = $v['name'];
                    }
                    $result[__($n['name'])] = $temp;
                }
                $groupdata = $result;
            }
        }


        $this->view->assign('groupdata', $groupdata);
    }

    /**
     * 数据查看
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {
        $erchart = $this->teamproject(false);

        if ($this->request->isAjax()) {
            return $this->success('', '', $erchart);
        }

        //项目支出分析
        $paylog_echart = $this->projectpaylog(false);
        $this->view->assign([
            'erchart' => $erchart,
            'count_price' => array_sum($erchart['hours']['data'][__('项目金额')]),
            'count_expenses' => array_sum($erchart['hours']['data'][__('支出金额')]),
            'count_project' => array_sum($erchart['hours']['data'][__('完成项目')]),
            'log_echart' => $erchart['log_echart'],
            'paylog_echart' => $paylog_echart
        ]);


        return $this->view->fetch();
    }

    /**
     * 项目报表
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $this->model = new  \app\admin\model\workteam\Project();

        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->fetchSql(false)
                ->count();

            //任务排序方法，如果是空,把重要的，将要过期的，未完成的任务排序在前面
            if ($sort == '') {
                $this->model->orderRaw("field(status,'0','1','2','3') ,level desc,id desc");
            } else {
                $this->model->order($sort, $order);
            }

            $list = $this->model
                ->where($where)
                ->with(['padmin' => function ($q) {
                    $q->field('id,nickname');
                }])
                ->limit($offset, $limit)->fetchSql(false)
                ->select();

            foreach ($list as $row) {
                //统计参与人数
                $row->admin_count = $row->admin_ids ? count(explode(',', $row->admin_ids)) : '0';
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig("statusList", $this->model->getStatusList());

        return $this->view->fetch();

    }


    /**
     * 财务统计
     * @internal
     */
    private function teamproject($is_ajax = true)
    {

        $startDate = $this->request->param('start_date');
        $endDate = $this->request->param('end_date');
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        $group_id = $this->request->param('group_id', isset($this->groupList[0]['id']) ? $this->groupList[0]['id'] : 0, 'intval');

        $owner_user_ids=array();
        if ($owner_user_id > 0) {
            $owner_user_ids[]=$owner_user_id;
        }elseif($group_id&&$group_id>0){

            $auth=new \addons\workteam\library\Auth();
            $owner_user_ids=$auth->getDepartmentAdminIds($this->auth,$group_id);
            if (!$owner_user_ids){
                $this->error("没有数据");
            }
        }


        $isnotrangeDate = empty($startDate) && empty($endDate);
        $nearly = '30';
        if ($isnotrangeDate) {
            $startDate = time();
            $nearly -= 1;
            $endDate = strtotime("-{$nearly} day");  // 最近30天日期
        }


        $this->model = new  \app\admin\model\workteam\Project();
        //获取项目数据
        $data = $this->model->getProjectEchart($startDate, $endDate, $owner_user_ids);

        $this->projectids = $this->model->getProjectIds($startDate, $endDate, $owner_user_ids, null, null);
        $accountlog = new Accountlog();
        //获取支出数据

        $data1 = $accountlog->getLogEchart($startDate, $endDate, $this->projectids ? $this->projectids : 0);
        $data['data'] = (array_merge($data['data'], $data1['data']));

        //获取支出类型统计
        $legendData = array();
        $seriesData = array();
        if ($this->projectids) {

            $lists = $accountlog->getLogTypeEchart($startDate, $endDate, $this->projectids);
            $name = 'workteam';
            $addon_config = get_addon_config($name);
            $addon_config['accounttype'];

            foreach ($lists as $k => $row) {
                if (isset($addon_config['accounttype'][$row['type']])) {
                    $seriesData[$k]['name'] = $legendData[] = $addon_config['accounttype'][$row['type']];
                } else {
                    $seriesData[$k]['name'] = $legendData[] = __("未知");
                }
                $seriesData[$k]['value'] = $row['money'];
            }
            $log_echart = ['legendData' => $legendData, 'seriesData' => $seriesData];
        }
        //无数据处理
        if (!count($seriesData))
            $log_echart = ['legendData' => [__('无')], 'seriesData' => [['name' => __('无'), 'value' => '0']]];


        $erchart = [
            'hours' => $data,
            'log_echart' => $log_echart,
        ];

        return $erchart;
    }

    /**
     * 项目支出分析
     */
    public function projectpaylog($is_ajax = true)
    {
        $project_id = $this->request->param('project_id', '', 'intval');

        $accountlog = new Accountlog();
        //获取支出类型统计
        $legendData = array();
        $seriesData = array();
        $data = array();//要返回的数据
        $lists = $accountlog->getLogTypeEchart(null, null, $project_id);
        $name = 'workteam';
        $addon_config = get_addon_config($name);
        $addon_config['accounttype'];

        $data['expenses'] = 0;
        foreach ($lists as $k => $row) {
            if (isset($addon_config['accounttype'][$row['type']])) {
                $seriesData[$k]['name'] = $legendData[] = $addon_config['accounttype'][$row['type']];
            } else {
                $seriesData[$k]['name'] = $legendData[] = __("未知");
            }
            $seriesData[$k]['value'] = $row['money'];
            $data['expenses'] += $row['money'];//总支出
        }
        $data['log_echart'] = ['legendData' => $legendData, 'seriesData' => $seriesData];

        //无数据处理
        if (!count($seriesData))
            $data['log_echart'] = ['legendData' => [__('无')], 'seriesData' => [['name' => __('无'), 'value' => '0']]];

        //获取项目总额
        $projectModel = new  \app\admin\model\workteam\Project();
        $project_id ? $projectModel->where('id', $project_id) : '';
        $data['p_price'] = $projectModel->sum('price');

        if (!$is_ajax) return $data;

        return $this->success('', '', $data);


    }


    /**
     * 添加
     * @internal
     */
    public function add()
    {
        $this->error();
    }

    /**
     * 编辑
     * @internal
     */
    public function edit($ids = null)
    {
        $this->error();
    }

    /**
     * 删除
     * @internal
     */
    public function del($ids = "")
    {
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * @Internal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $this->model = new  \app\admin\model\workteam\Project();
        $this->request->request(['showField' => 'name']);
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }
}
